﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using DevExpress.XtraEditors;
using DevExpress.XtraNavBar;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraWaitForm;
using DevExpress.XtraGrid.Views.Card;
using DevExpress.XtraGrid.Views.Card.ViewInfo;
using CsvHelper;
using Model;
using BartonExtension;
using ResponseObject;

namespace Backend
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm
    {
        public MainForm()
        {
            InitializeComponent();
            Init();
        }

        private void navBarControl1_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
        {
            Master_Detail_Mapper();
        }

        /**
         * Code group : custom functions
         **/
        void Init()
        {
            navBarControl1.ActiveGroup = gpBrand;
            Master_Detail_Mapper();
        }

        void Master_Detail_Mapper()
        {
            NavBarGroup activeGroup = navBarControl1.ActiveGroup;
            if(activeGroup.Name.Equals("gpBrand"))
            {
                dataView.MainView = gvBrand;
                dataView.DataSource = DataSourcePool.brands;
            }
            else if(activeGroup.Name.Equals("gpCatalog"))
            {
                dataView.MainView = gvCatalog;
                dataView.DataSource = DataSourcePool.catalogs;
            }
            else if(activeGroup.Name.Equals("gpMall"))
            {
                dataView.MainView = gvMall;
                dataView.DataSource = DataSourcePool.malls;
            }
            else if(activeGroup.Name.Equals("gpStore"))
            {
                dataView.MainView = gvStore;
                dataView.DataSource = DataSourcePool.stores;
            }
            else if(activeGroup.Name.Equals("gpActivity"))
            {
                dataView.MainView = gvActivity;
                dataView.DataSource = DataSourcePool.activities;
            }
            dataView.MainView.RefreshData();
        }

        /**
         *  Events
         **/
        private void brand_item_update_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            gvBrand.CloseEditor();

            PostParams param = new PostParams();
            List<Brand> willUpdate = new List<Brand>();
            DataSourcePool.brands.ForEach(x =>
                {
                    Brand brand = x;
                    byte[] buffer = Encoding.UTF8.GetBytes(x.desc);
                    brand.desc = Convert.ToBase64String(buffer);
                    willUpdate.Add(brand);
                });
            byte[] bf = Encoding.UTF8.GetBytes(willUpdate.ToJson());

            param.addParam("batchJson", Convert.ToBase64String(bf));

            HttpPost post = new HttpPost("{0}/apis/ZK_BackEndService.asmx/BatchInsertBrands".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
            post.post((json, err) =>
                {
                    if (err != null)
                    {
                        Utils.IndicatorShowHide(this, false);
                        XtraMessageBox.Show(err.Message);
                        return;
                    }
                    ZKResponse response = json.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                    if (response.isProcessSuccess)
                    {
                        //Reload
                        WebServiceHelper.LoadBrands((lb, error) =>
                            {
                                if(error != null)
                                {
                                    Utils.IndicatorShowHide(this, false);
                                    XtraMessageBox.Show("Fail to reload brands");
                                }
                                else
                                {
                                    DataSourcePool.brands = lb;
                                    this.Invoke(new Action(() =>
                                        {
                                            Master_Detail_Mapper();
                                            gvBrand.RefreshData();
                                            Utils.IndicatorShowHide(this, false);
                                        }));
                                }
                            });
                        XtraMessageBox.Show("Remote brands updated");
                    }
                    else
                    {
                        XtraMessageBox.Show("Error : {0}".FormatWith(response.errMsg));
                    }
                });
        }

        private void brand_item_import_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                dialog.Filter = "csv file|*.csv";
                dialog.Multiselect = false;
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Utils.IndicatorShowHide(this, true);
                    //Load Brand
                    List<Brand> brands = new List<Brand>();
                    using (TextReader sr = new StreamReader(dialog.FileName, Encoding.UTF8))
                    {
                        using (CsvReader cr = new CsvReader(sr))
                        {
                            while (cr.Read())
                            {
                                Brand brand = new Brand()
                                {
                                    code = cr.GetField<string>("code"),
                                    title = cr.GetField<string>("title"),
                                    title_origin = cr.GetField<string>("title_origin"),
                                    location = cr.GetField<string>("location"),
                                    desc = cr.GetField<string>("desc"),
                                    level = cr.GetField<float>("level")
                                };
                                brands.Add(brand);
                            }
                        }
                    }
                    DataSourcePool.brands = brands;
                    dataView.FocusedView.RefreshData();
                    Utils.IndicatorShowHide(this, false);
                }
            }
        }

        private void brand_item_download_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            PostParams param = new PostParams();
            param.addParam("page_index", 0);
            param.addParam("page_capacity", 1000);
            param.addParam("lan_tag", "cn");
            HttpPost post = new HttpPost("{0}/apis/ZK_GeneralService.asmx/brands".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
            post.post((json,err) =>
                {
                    if(err != null)
                    {
                        Utils.IndicatorShowHide(this, false);
                        XtraMessageBox.Show(err.Message);
                        return;
                    }
                    ZKResponse response = json.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                    if(response.isProcessSuccess)
                    {
                        List<Brand> brands = response.userinfo.ToString().FromJson<List<Brand>>();
                        DataSourcePool.brands = brands;
                        this.Invoke(new Action(() =>
                            {
                                Master_Detail_Mapper();
                                gvBrand.RefreshData();
                                Utils.IndicatorShowHide(this, false);
                            }));
                    }
                });
        }

        private void gvBrand_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int handle = e.RowHandle;
            if (handle >= 0)
            {
                int dataSourceIndex = gvBrand.GetDataSourceRowIndex(handle);
                System.Reflection.PropertyInfo info = DataSourcePool.brands[dataSourceIndex].GetType().GetProperty(e.Column.FieldName);
                info.SetValue(DataSourcePool.brands[dataSourceIndex], e.Value, null);
            }
            else
            {
                
            }
        }

        private void catalog_item_download_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            DataSourcePool.catalogs.Clear();
            PostParams param = new PostParams();
            param.addParam("lan_tag", "all");
            HttpPost post = new HttpPost("{0}/apis/ZK_GeneralService.asmx/catalogs".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
            post.post((json, err) =>
            {
                if (err != null)
                {
                    this.Invoke(new Action(() =>
                        {
                            Utils.IndicatorShowHide(this, false);
                        }));
                    XtraMessageBox.Show(err.Message);
                    return;
                }
                ZKResponse response = json.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                if (response.isProcessSuccess)
                {
                    List<Catalog> catalogs = response.userinfo.ToString().FromJson<List<Catalog>>();
                    DataSourcePool.catalogs = catalogs;
                    this.Invoke(new Action(() =>
                    {
                        Master_Detail_Mapper();
                        gvCatalog.RefreshData();
                        Utils.IndicatorShowHide(this, false);
                    }));
                }
                else
                {
                    this.Invoke(new Action(() =>
                    {
                        Master_Detail_Mapper();
                        gvCatalog.RefreshData();
                        Utils.IndicatorShowHide(this, false);
                        XtraMessageBox.Show(response.errMsg); 
                    }));
                }
            });
        }

        private void catalog_item_update_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            gvCatalog.CloseEditor();

            PostParams param = new PostParams();
            byte[] bf = Encoding.UTF8.GetBytes(DataSourcePool.catalogs.ToJson());
            param.addParam("batchJson", Convert.ToBase64String(bf));

            HttpPost post = new HttpPost("{0}/apis/ZK_BackEndService.asmx/BatchInsertCatalogs".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
            post.post((json, err) =>
            {
                if (err != null)
                {
                    Utils.IndicatorShowHide(this, false);
                    XtraMessageBox.Show(err.Message);
                    return;
                }
                ZKResponse response = json.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                if (response.isProcessSuccess)
                {
                    WebServiceHelper.LoadCatalogs((resp, error) =>
                        {
                            DataSourcePool.catalogs = resp;
                            this.Invoke(new Action(() =>
                                {
                                    Master_Detail_Mapper();
                                    gvCatalog.RefreshData();
                                    Utils.IndicatorShowHide(this, false);
                                    XtraMessageBox.Show("Remove catalog updated");
                                }));
                        });
                }
                else
                {
                    XtraMessageBox.Show("Error : {0}".FormatWith(response.errMsg));
                }
            });
        }

        private void mall_item_download_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            HttpPost post = new HttpPost("{0}/apis/ZK_GeneralService.asmx/malls".FormatWith(AddressPool.ServerAddr), string.Empty);
            post.get((json, err) =>
                {
                    this.Invoke(new Action(() =>
                        {
                            if (err != null)
                            {
                                Utils.IndicatorShowHide(this, false);
                                XtraMessageBox.Show(err.Message);
                                return;
                            }
                            ZKResponse response = json.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                            if (response.isProcessSuccess)
                            {
                                List<Mall> malls = response.userinfo.ToString().FromJson<List<Mall>>();
                                DataSourcePool.malls = malls;
                                Master_Detail_Mapper();
                                gvMall.RefreshData();
                                Utils.IndicatorShowHide(this, false);
                            }
                        }));
                });
        }

        private void mall_item_update_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            if(DataSourcePool.malls.Count == 0)
            {
                XtraMessageBox.Show("No data for updating");
                return;
            }
            Utils.IndicatorShowHide(this, true);
            gvMall.CloseEditor();

            PostParams param = new PostParams();
            byte[] bf = Encoding.UTF8.GetBytes(DataSourcePool.malls.ToJson());
            param.addParam("batchJson", Convert.ToBase64String(bf));

            HttpPost post = new HttpPost("{0}/apis/ZK_BackendService.asmx/BatchInsertMalls".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
            post.post((json, err) =>
            {
                this.Invoke(new Action(() =>
                    {
                        if (err != null)
                        {
                            Utils.IndicatorShowHide(this, false);
                            XtraMessageBox.Show(err.Message);
                            return;
                        }
                        ZKResponse response = json.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                        if (response.isProcessSuccess)
                        {
                            WebServiceHelper.LoadMalls((resp, error) =>
                            {
                                this.Invoke(new Action(() =>
                                    {
                                        DataSourcePool.malls = resp;
                                        Master_Detail_Mapper();
                                        gvMall.RefreshData();
                                        Utils.IndicatorShowHide(this, false);
                                        XtraMessageBox.Show("Remote catalog updated");
                                    }));
                            });
                        }
                        else
                        {
                            Utils.IndicatorShowHide(this, false);
                            XtraMessageBox.Show("Error : {0}".FormatWith(response.errMsg));
                        }
                    }));
                
            });
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }

        private void brand_item_add_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            WebServiceHelper.LoadBrands((src, err) =>
                {
                    if (err != null)
                    {
                        this.Invoke(new Action(() =>
                        {
                            Utils.IndicatorShowHide(this, false);
                        }));
                        XtraMessageBox.Show(err.Message);
                        return;
                    }
                    //Get un-updated rows
                    if (DataSourcePool.brands.Count > 0)
                    {
                        List<Brand> newAddData = DataSourcePool.brands.Where((b, bl) =>
                            {
                                return b.ID == -1;
                            }).ToList();
                        src.AddRange(newAddData);
                    }
                    DataSourcePool.brands = src;

                    this.Invoke(new Action(() =>
                    {
                        Master_Detail_Mapper();
                        gvBrand.RefreshData();
                        Utils.IndicatorShowHide(this, false);

                        using (FrmBrand frm = new FrmBrand())
                        {
                            frm.ShowDialog();
                            if (frm.result == System.Windows.Forms.DialogResult.OK)
                            {
                                Brand brand = frm.brand;
                                DataSourcePool.brands.Add(brand);
                                Master_Detail_Mapper();
                            }
                        }
                    }));
                });
        }

        private void catalog_item_add_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            WebServiceHelper.LoadCatalogs((src, err) =>
            {
                if (err != null)
                {
                    Utils.IndicatorShowHide(this, false);
                    XtraMessageBox.Show(err.Message);
                    return;
                }
                //Get un-updated rows
                if (DataSourcePool.catalogs.Count > 0)
                {
                    List<Catalog> newAddData = DataSourcePool.catalogs.Where((c, bl) =>
                    {
                        return c.ID == -1;
                    }).ToList();
                    src.AddRange(newAddData);
                }
                DataSourcePool.catalogs = src;
                this.Invoke(new Action(() =>
                {
                    Master_Detail_Mapper();
                    gvCatalog.RefreshData();
                    Utils.IndicatorShowHide(this, false);
                    using (FrmCatalog frm = new FrmCatalog())
                    {
                        frm.ShowDialog();
                        if (frm.result == System.Windows.Forms.DialogResult.OK)
                        {
                            Catalog catalog = frm.catalog;
                            DataSourcePool.catalogs.Add(catalog);
                            Master_Detail_Mapper();
                            gvCatalog.RefreshData();
                        }
                    }
                }));
            });
        }

        private void mall_item_add_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            WebServiceHelper.LoadMalls((src, err) =>
                {
                    if (err != null)
                    {
                        this.Invoke(new Action(() =>
                        {
                            Utils.IndicatorShowHide(this, false);
                        }));
                        XtraMessageBox.Show(err.Message);
                        return;
                    }
                    //Get un-updated rows
                    if (DataSourcePool.malls.Count > 0)
                    {
                        List<Mall> newAddData = DataSourcePool.malls.Where((m, bl) =>
                        {
                            return m.ID == -1;
                        }).ToList();
                        src.AddRange(newAddData);
                    }
                    DataSourcePool.malls = src;
                    this.Invoke(new Action(() =>
                        {
                            Master_Detail_Mapper();
                            gvMall.RefreshData();
                            Utils.IndicatorShowHide(this, false);
                            using (FrmMall frm = new FrmMall())
                            {
                                frm.ShowDialog();
                                if (frm.result == System.Windows.Forms.DialogResult.OK)
                                {
                                    Mall mall = frm.mall;
                                    DataSourcePool.malls.Add(mall);
                                    Master_Detail_Mapper();
                                    gvMall.RefreshData();
                                }
                            }
                        }));
                });
        }

        private void store_item_add_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            using(FrmStore frm = new FrmStore())
            {
                frm.ShowDialog();
            }
        }

        private void catalog_item_delete_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            
            //Post delete process to server
            try
            {
                int id = gvCatalog.GetRowCellValue(gvCatalog.FocusedRowHandle, "ID").toInt32().Value;
                string code = gvCatalog.GetRowCellValue(gvCatalog.FocusedRowHandle, "code").ToString();
                int layer = gvCatalog.GetRowCellValue(gvCatalog.FocusedRowHandle, "layer").toInt32().Value;
                if(id == -1)
                {
                    int indexToDelete = DataSourcePool.catalogs.FindIndex(x =>
                        {
                            return x.code.Equals(code) && x.layer == layer;
                        });
                    DataSourcePool.catalogs.RemoveAt(indexToDelete);
                    Master_Detail_Mapper();
                    gvCatalog.RefreshData();
                    Utils.IndicatorShowHide(this, false);
                    XtraMessageBox.Show("Catalog : {0} is deleted from database".FormatWith(code));
                }
                else
                {
                    PostParams param = new PostParams();
                    param.addParam("id", id);
                    HttpPost post = new HttpPost("{0}/apis/ZK_BackEndService.asmx/DeleteCatalog".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
                    post.post((resp, err) =>
                    {
                        if(err != null)
                        {
                            this.Invoke(new Action(() =>
                            {
                                Utils.IndicatorShowHide(this, false);
                            }));
                            XtraMessageBox.Show(err.Message);
                            return;
                        }
                        ZKResponse response = resp.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                        if (response.isProcessSuccess)
                        {
                            WebServiceHelper.LoadCatalogs((data, error) =>
                            {
                                DataSourcePool.catalogs = data;
                                this.Invoke(new Action(() =>
                                {
                                    Master_Detail_Mapper();
                                    gvCatalog.RefreshData();
                                    Utils.IndicatorShowHide(this, false);
                                    XtraMessageBox.Show("Catalog : {0} is deleted from database".FormatWith(code));
                                }));
                            });
                        }
                        else
                        {
                            XtraMessageBox.Show(response.errMsg);
                        }
                    });
                }
            }
            catch(Exception ex)
            {
                Utils.IndicatorShowHide(this, false);
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void brand_item_delete_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);

            //Post delete process to server
            try
            {
                int id = gvBrand.GetRowCellValue(gvBrand.FocusedRowHandle, "ID").toInt32().Value;
                string code = gvBrand.GetRowCellValue(gvBrand.FocusedRowHandle, "code").ToString();
                if (id == -1)
                {
                    int indexToDelete = DataSourcePool.brands.FindIndex(x =>
                    {
                        return x.code.Equals(code);
                    });
                    DataSourcePool.brands.RemoveAt(indexToDelete);
                    gvBrand.DeleteRow(gvBrand.FocusedRowHandle);
                    Utils.IndicatorShowHide(this, false);
                    XtraMessageBox.Show("Brand : {0} is deleted from database".FormatWith(code));
                }
                else
                {
                    PostParams param = new PostParams();
                    param.addParam("id", id);
                    HttpPost post = new HttpPost("{0}/apis/ZK_BackEndService.asmx/DeleteBrand".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
                    post.post((resp, err) =>
                    {
                        ZKResponse response = resp.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                        if (response.isProcessSuccess)
                        {
                            WebServiceHelper.LoadBrands((data, error) =>
                                {
                                    if(error != null)
                                    {
                                        this.Invoke(new Action(() =>
                                        {
                                            Utils.IndicatorShowHide(this, false);
                                        }));
                                        XtraMessageBox.Show(error.Message);
                                        return;
                                    }
                                    DataSourcePool.brands = data;
                                    this.Invoke(new Action(() =>
                                    {
                                        Master_Detail_Mapper();
                                        gvBrand.RefreshData();
                                        Utils.IndicatorShowHide(this, false);
                                        XtraMessageBox.Show("Brand : {0} is deleted from database".FormatWith(code));
                                    }));
                                });
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                Utils.IndicatorShowHide(this, false);
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void mall_item_delete_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            int handle = gvMall.FocusedRowHandle;
            int ID = gvMall.GetFocusedRowCellValue("ID").toInt32().Value;
            if(ID == -1)
            {
                int dsIndex = DataSourcePool.malls.FindIndex(x =>
                    {
                        return x.street.Equals(gvMall.GetFocusedRowCellValue("street")) &&
                               x.region.Equals(gvMall.GetFocusedRowCellValue("region")) &&
                               x.name.Equals(gvMall.GetFocusedRowCellValue("name"));
                    });
                DataSourcePool.malls.RemoveAt(dsIndex);
                gvMall.RefreshData();
            }
            else
            {
                PostParams param = new PostParams();
                param.addParam("id", ID);
                HttpPost post = new HttpPost("{0}/apis/ZK_BackendService.asmx/DeleteMall".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
                post.post((data, err) =>
                    {
                        if(err != null)
                        {
                            XtraMessageBox.Show(err.Message);
                            return;
                        }
                        ZKResponse response = data.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                        if(response.isProcessSuccess)
                        {
                            WebServiceHelper.LoadMalls((resp, error) =>
                            {
                                this.Invoke(new Action(() =>
                                {
                                    DataSourcePool.malls = resp;
                                    Master_Detail_Mapper();
                                    gvMall.RefreshData();
                                    Utils.IndicatorShowHide(this, false);
                                    XtraMessageBox.Show("Delete success");
                                }));
                            });
                        }
                        else
                        {
                            XtraMessageBox.Show(response.errMsg);
                        }
                    });
            }
        }

        private void tools_item_batch_thumbnail_generator_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            using(ThumbGenerator frm = new ThumbGenerator())
            {
                frm.ShowDialog();
            }
        }

        private void tools_item_image_grid_xml_editor_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            using(XMLGenerator frm = new XMLGenerator())
            {
                frm.ShowDialog();
            }
        }

        private void store_item_download_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            WebServiceHelper.LoadStores((s, err) =>
                {
                    if(err != null)
                    {
                        this.Invoke(new Action(() =>
                            {
                                Utils.IndicatorShowHide(this, false);
                                XtraMessageBox.Show(err.Message);
                            }));
                        return;
                    }
                    this.Invoke(new Action(() =>
                        {
                            DataSourcePool.stores = s;
                            Master_Detail_Mapper();
                            gvStore.RefreshData();
                            Utils.IndicatorShowHide(this, false);
                        }));
                });
        }

        private void store_item_delete_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            try
            {
                int handle = gvStore.FocusedRowHandle;
                int id = gvStore.GetRowCellValue(handle, "ID").toInt32().Value;
                string name = gvStore.GetRowCellValue(handle,"title").ToString();
                PostParams param = new PostParams();
                param.addParam("store_id", id);
                HttpPost post = new HttpPost("{0}/apis/ZK_BackEndService.asmx/delete_store".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
                post.post((s, err) =>
                    {
                        if(err != null)
                        {
                            Utils.IndicatorShowHide(this, false);
                            XtraMessageBox.Show(err.Message);
                            return;
                        }
                        ZKResponse response = s.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                        if(response.isProcessSuccess)
                        {
                            WebServiceHelper.LoadStores((data, error) =>
                                {
                                    if(error != null)
                                    {
                                        this.Invoke(new Action(() =>
                                            {
                                                Utils.IndicatorShowHide(this, false);
                                                XtraMessageBox.Show(error.Message);
                                            }));
                                        return;
                                    }
                                    DataSourcePool.stores = data;
                                    this.Invoke(new Action(() =>
                                        {
                                            Master_Detail_Mapper();
                                            gvStore.RefreshData();
                                            Utils.IndicatorShowHide(this, false);
                                            XtraMessageBox.Show("Store : {0} deleted from db".FormatWith(name));
                                        }));
                                });
                        }
                        else
                        {
                            this.Invoke(new Action(() =>
                                {
                                    Utils.IndicatorShowHide(this, false);
                                    XtraMessageBox.Show(response.errMsg);
                                }));
                        }
                    });
            }
            catch(Exception ex)
            {
                Utils.IndicatorShowHide(this, false);
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void gvStore_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if(e.Clicks == 2)
            {
                
            }
        }

        private void gvMall_DoubleClick(object sender, EventArgs e)
        {
            CardView cv = (CardView)sender;
            Point pt = cv.GridControl.PointToClient(Control.MousePosition);
            var info = cv.CalcHitInfo(pt);
            if(info.InCard)
            {
                int handle = info.RowHandle;
                Mall mall = gvMall.GetRow(handle) as Mall;
                using(FrmMall frm = new FrmMall(mall))
                {
                    frm.ShowDialog();
                    if(frm.result == System.Windows.Forms.DialogResult.OK)
                    {
                        Mall m = frm.mall;
                        int dataSourceIndex = gvMall.GetDataSourceRowIndex(handle);
                        DataSourcePool.malls[dataSourceIndex] = m;
                        Master_Detail_Mapper();
                        gvMall.RefreshData();
                    }
                }
            }

        }

        private void gvCatalog_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if(e.Clicks == 2)
            {
                int handle = e.RowHandle;
                Catalog catalog = gvCatalog.GetRow(handle) as Catalog;
                using(FrmCatalog frm = new FrmCatalog(catalog))
                {
                    frm.ShowDialog();
                    if(frm.result == System.Windows.Forms.DialogResult.OK)
                    {
                        Catalog c = frm.catalog;
                        int dataSourceIndex = gvCatalog.GetDataSourceRowIndex(handle);
                        DataSourcePool.catalogs[dataSourceIndex] = c;
                        Master_Detail_Mapper();
                        gvCatalog.RefreshData();
                    }
                }
            }
        }

        private void store_item_import_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            using (OpenFileDialog dialog = new OpenFileDialog())
            {
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string csvFile = dialog.FileName;
                    List<Dictionary<string, string>> stores = new List<Dictionary<string, string>>();
                    using (TextReader tr = File.OpenText(csvFile))
                    {
                        using (CsvReader cr = new CsvReader(tr))
                        {
                            while (cr.Read())
                            {
                                Dictionary<string, string> store = new Dictionary<string, string>();
                                store.Add("store_id", cr["store_id"].HtmlDecode());
                                store.Add("title", cr["title"].HtmlDecode());
                                store.Add("type", cr["type"]);
                                store.Add("frequency", cr["frequency"]);
                                store.Add("duration", cr["duration"]);
                                store.Add("level", cr["level"]);
                                store.Add("mall_code", cr["mall_code"]);
                                store.Add("in_mall_location", cr["in_mall_location"].HtmlDecode());
                                store.Add("lat", cr["lat"]);
                                store.Add("lng", cr["lng"]);
                                store.Add("live_time", cr["live_time"]);
                                store.Add("catalogs", cr["catalogs"]);
                                store.Add("desc", cr["desc"].HtmlDecode().Replace(":","：")
                                                                         .Replace(",","，")
                                                                         .Replace("{","{")
                                                                         .Replace("\"","”"));
                                store.Add("tel", cr["tel"].HtmlDecode());
                                stores.Add(store);
                            }
                        }
                    }
                    PostParams param = new PostParams();
                    string json = stores.ToJson();
                    byte[] bf = Encoding.UTF8.GetBytes(json);
                    param.addParam("batchJson", Convert.ToBase64String(bf));
                    HttpPost post = new HttpPost("{0}/apis/ZK_BackEndService.asmx/BatchImportStores".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
                    post.post((x, ex) =>
                        {
                            if(ex != null)
                            {
                                XtraMessageBox.Show(ex.Message);
                                return;
                            }
                            ZKResponse response = x.FromJson<Dictionary<string,object>>()["d"].ToString().FromJson<ZKResponse>();
                            if(response.isProcessSuccess)
                            {
                                XtraMessageBox.Show("Done");
                            }
                            else
                            {
                                XtraMessageBox.Show(response.errMsg);
                            }
                        });
                }
            }
        }

        private void activity_item_add_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            using(FrmActivity frm = new FrmActivity())
            {
                frm.ShowDialog();
                if(frm.result == System.Windows.Forms.DialogResult.OK)
                {
                    Activity activity = frm.activity;
                    DataSourcePool.activities.Add(activity);
                    Master_Detail_Mapper();
                }
            }
        }

        private void activity_item_download_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            WebServiceHelper.LoadActs((a, ex) =>
                {
                    if(ex!=null)
                    {
                        Utils.IndicatorShowHide(this, false);
                        XtraMessageBox.Show(ex.Message);
                        return;
                    }
                    this.Invoke(new Action(() =>
                        {
                            DataSourcePool.activities = a;
                            Master_Detail_Mapper();
                            gvActivity.RefreshData();
                        }));
                    Utils.IndicatorShowHide(this, false);
                });
        }

        private void activity_item_upload_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            if(DataSourcePool.activities.Count == 0)
            {
                XtraMessageBox.Show("No data for updating");
                return;
            }
            Utils.IndicatorShowHide(this, true);
            PostParams param = new PostParams();
            param.addParam("batchJson", DataSourcePool.activities.ToJson().toBase64());
            HttpPost post = new HttpPost("{0}/apis/ZK_BackendService.asmx/BatchInsertActs".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
            post.post((s, er) =>
                {
                    if(er != null)
                    {
                        Utils.IndicatorShowHide(this, false);
                        XtraMessageBox.Show(er.Message);
                        return;
                    }
                    ZKResponse response = s.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                    if (response.isProcessSuccess)
                    {
                        WebServiceHelper.LoadActs((a, err) =>
                            {
                                if(err != null)
                                {
                                    Utils.IndicatorShowHide(this, false);
                                    XtraMessageBox.Show(err.Message);
                                    return;
                                }
                                this.Invoke(new Action(() =>
                                    {
                                        DataSourcePool.activities = a;
                                        Master_Detail_Mapper();
                                        gvActivity.RefreshData();
                                    }));
                                Utils.IndicatorShowHide(this, false);
                            });
                    }
                    else
                    {
                        Utils.IndicatorShowHide(this, false);
                        XtraMessageBox.Show(response.errMsg);
                    }
                });
        }

        private void activity_item_import_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            using(OpenFileDialog dialog = new OpenFileDialog())
            {
                if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string csv = dialog.FileName;
                    List<Dictionary<string, object>> acts = new List<Dictionary<string, object>>();
                    using(TextReader tr = new StreamReader(csv,Encoding.UTF8))
                    {
                        using(CsvReader cr = new CsvReader(tr))
                        {
                            while(cr.Read())
                            {
                                Dictionary<string, object> act = new Dictionary<string, object>();
                                foreach(string fieldHeader in cr.FieldHeaders)
                                {
                                    act.Add(fieldHeader, cr[fieldHeader]);
                                }
                                acts.Add(act);
                            }
                        }
                    }
                    PostParams param = new PostParams();
                    param.addParam("batchJson", acts.ToJson().toBase64());
                    HttpPost post = new HttpPost("{0}/apis/ZK_BackendService.asmx/BatchImportActivities".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
                    post.post((s, er) =>
                        {
                            if(er != null)
                            {
                                XtraMessageBox.Show(er.Message);
                                return;
                            }
                            ZKResponse response = s.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                            if(response.isProcessSuccess)
                            {
                                XtraMessageBox.Show("Done");
                            }
                            else
                            {
                                XtraMessageBox.Show(response.errMsg);
                            }
                        });
                }
            }
        }

        private void tool_item_g_seed_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            using(OpenFileDialog dialog = new OpenFileDialog())
            {
                if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string csvFile = dialog.FileName;
                    List<Dictionary<string, object>> seeds = new List<Dictionary<string, object>>();
                    using(TextReader tr = new StreamReader(csvFile))
                    {
                        using(CsvReader cr = new CsvReader(tr))
                        {
                            while(cr.Read())
                            {
                                Dictionary<string, object> seed = new Dictionary<string, object>();
                                Dictionary<string,object> data = new Dictionary<string,object>();
                                seed.Add("code", cr["CODE"].ToString());
                                data.Add("1",cr["L1"].ToString());
                                data.Add("2", cr["L2"].ToString());
                                data.Add("3", cr["L3"].ToString());
                                data.Add("4", cr["L4"].ToString());
                                data.Add("5", cr["L5"].ToString());
                                seed.Add("data", data);
                                seeds.Add(seed);
                            }
                        }
                    }
                    PostParams p = new PostParams();
                    p.addParam("json", seeds.ToJson().toBase64());
                    HttpPost post = new HttpPost("{0}/apis/zk_backendservice.asmx/GenerateSeedImport".FormatWith(AddressPool.ServerAddr),p.jsonSerialize());
                    post.post((s,er)=>{
                        ZKResponse response = s.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                        if (response.isProcessSuccess)
                        {
                            XtraMessageBox.Show("da dai ji");
                            return;
                        }
                    });
                }
            }
        }
    }
}